/**
 * Javascript source file for reports.php
 * 
 * Loading of reports for details view is currently done in an async way but could be fulfilled also from the store buffer.
 */

var searchstore = null;
var delete_box_done = new Array();

// whenever there are changes at the array, adjust all methods that refer to the array or its index!
// var column_header is defined at reports.php because of language dependancy
var column_keys = new Array("address","moon","ally","g_planet","player","datetime","depth","all_resources","all_resis","fleet_resis","defence_resis","metal","crystal","deuterium","energy","kt","gt","lj","sj","krz","ss","kolo","rec","spio","bomb","zerri","ds","skrz","sat","rak","ll","sl","ion","gauss","plasma","ksk","gsk","arak","irak","memi","krimi","deutsyn","solar","fusion","robo","nani","rawe","mesp","krissp","deutsp","folab","terra","allydep","raksilo","mbase","sensor","sprungtor","spiolvl","computech","waffentech","schildtech","rpz","energytech","hypertech","vbt","impulse","hra","lasertech","iontech","plasmatech","forschungsnetz","expedition","gravi");

function start_search() {
	dojo.byId("messageAreaContent").innerHTML = "";
	dojo.byId("messageArea").style.display    = "none";
	searchstore = null;
	
	for (var i=1; i<8; i++) {
		if (dijit.byId("search"+i).get("open") == true) {
			dijit.byId("search"+i).toggle();
		}
	}
	
	var xhrArgs = {
	        url: "ajax/ajax_report.php?type=search",
	        form: dojo.byId("report1"),
	        handleAs: "json",
	        load: function(jsonData) {
	        	if (jsonData.messages != null) {
	        		showMessages(jsonData.messages);
	        	}
	        	
	        	dojo.byId("result_view").style.display = "block";

	        	// change store content
	        	var data = {
	        	      identifier: 'id',
	        	      items: jsonData.items
	        	};
	        	searchstore = new dojo.data.ItemFileWriteStore({id:"searchstore", data: data});
	        	
	        	searchstore.comparatorMap={}
	        	for (var i=0; i<column_keys.length; i++) {
	        		switch (column_keys[i]) {
					case "player":
					case "ally":
					case "g_planet":
						// sort case insensitive
						searchstore.comparatorMap[column_keys[i]] = function (a, b) { return a.localeCompare(b); }
						break;
					case "address":
						searchstore.comparatorMap[column_keys[i]] = galaxytool_compare_coordinates;
						break;
					case "moon":
					case "datetime":
						// no sort function needed
						break;

					case "depth":
						searchstore.comparatorMap[column_keys[i]] = galaxytool_compare_integer;
						break;

					default:
						// numeric sorting
						searchstore.comparatorMap[column_keys[i]] = galaxytool_compare_integer;
						break;
					}
	        		
	        	}
        		searchgrid.setStore(searchstore);
        		dojo.byId("results").innerHTML = NumberFormat(jsonData.items.length);

	        },
	        error: function(error) {
				console.log("Error:");
				console.log(error);
	        }
	}	
	dojo.xhrPost(xhrArgs);	
	return false; // to avoid form submit	
}

function format_number(val, rowIdx, cell) {
	return NumberFormat(val);
}
function format_address(val, rowIdx, cell) {
	var coordinates = val.split(":");
	if (coordinates.length != 3) return;
	
	return '<a href="galaxyview.php?gala='+coordinates[0]+'&system='+coordinates[1]+'">'+val+'</a>';
}
function format_scandepth(val, rowIdx, cell) {
	switch (val) {
		case '1': return column_header.depth.resources; break;
		case '2': return column_header.depth.fleet; break;
		case '3': return column_header.depth.defence; break;
		case '4': return column_header.depth.buildings; break;
		case '5': return column_header.depth.research; break;
		default: return val; break;
	}
}

function format_datetime(val, rowIdx, cell) {
	cell.customClasses.push("datetime_text");
	val = val.replace(/(\d+\-)(\d+\-\d+\s\d+\:\d+)(\:\d+)/g, "$2");
	return val;
}

function format_moon(val, rowIdx, cell) {
	if (val == "false") return "";
	
	return "M";
}

function format_ally(val, rowIdx, cell) {
	val = dojo.fromJson(val);
	if (val.id == 0 || val.id == null) return "";
	
	var value = "<a href=\"allyinformation.php?id="+val.id+"\" class=\""+val.s+"\">"+val.n+"</a>";
	
	return value;
}

function format_player(val, rowIdx, cell) {
	val = dojo.fromJson(val);
	if (val.id == 0 || val.id == null) return "";
	
	var value = "<a href=\"playerinformation.php?id="+val.id+"\" class=\""+val.s+"\">"+val.n+"</a>";
	
	return value;
}


function format_second_column(val, rowIdx, cell) {
	var moon = searchstore.getValue(searchgrid.getItem(rowIdx), "moon");
	
	var detailsIcon = '<img onclick=\'show_report("'+val+'",'+moon+')\' src="../images/magnifier2.png" height=16" width="16" style="cursor: pointer;">';
	return detailsIcon;
}
function format_first_column(val, rowIdx, cell) {
	// create checkbox for each cell only once
	if (delete_box_done[val] == true) {
		return dijit.byId("deletebox"+val);
	}
	delete_box_done[val] = true;
	try {
		var checkBox = new dijit.form.CheckBox({
			id: "deletebox"+val,
			name: "checkBox",
			value: "true",
			checked: false,
		});
		return checkBox;
	} catch(e) {
		console.log(e);
		return "";
	}
}

function change_layout() {
	var layout = new Array();
	layout[0] = new Array();
	
	var cookie_data = "";
	
	// default columns which cannot be customized
	layout[0].push( {
		name: ' ', 
		field: 'id', 
		formatter: format_first_column, 
		cellClasses :'default_reports_cell', 
		width: '25px' } );	
	layout[0].push( {
		name: ' ', 
		field: 'address', 
		formatter: format_second_column, 
		cellClasses :'default_reports_cell', 
		width: '25px' } );		
	
	var formatter = { 
			address : format_address,
			moon : format_moon,
			ally: format_ally,
			player : format_player,
			datetime : format_datetime,
			depth : format_scandepth,
			others : format_number,
	}
	
	cookie_data += "address";
	for (var i=0; i<column_keys.length; i++) {
		
		if (dijit.byId("column_"+column_keys[i]).get("value") == "true") { 
			cookie_data += "|"+column_keys[i];
			
			var format = formatter.others;
			if (formatter[column_keys[i]]) {
				format = formatter[column_keys[i]];
			}
			
			var width;
				switch (column_keys[i]) {
				case 'address': width = "75px"; break;
				case 'moon': width = "40px"; break;
				case 'datetime': width = "75px"; break;
				default: width = "100px"; break;
			}
			
			var column_name;
			if (column_keys[i] == "depth") {
				column_name =column_header.depth.header;
			} else {
				column_name = column_header[column_keys[i]];	
			}
			 
			layout[0].push( {
				name: column_name, 
				field: column_keys[i], 
				formatter: format, 
				cellClasses :'default_reports_cell', 
				width: width } );
		
		}
		
	}
	
	if (layout[0].length == 2) { // 2 default columns
		// default Layout (fields must be set to true at reports.php!)
		 var layout = [[
		                {name: column_header.address, field: 'address', formatter: format_address, cellClasses :'default_reports_cell', width:'75px' },
		                {name: column_header.moon, field: 'moon', formatter: format_moon, cellClasses :'default_reports_cell', width: '40px' },
		                {name: column_header.ally, field: 'ally', formatter: format_ally, cellClasses :'default_reports_cell', width:'100px' },
		                {name: column_header.player, field: 'player', formatter: format_player, cellClasses :'default_reports_cell', width:'100px' },
		                {name: column_header.datetime, field: 'datetime', formatter: format_datetime, cellClasses :'default_reports_cell', width: '75px' },
		                {name: column_header.metal, field: 'metal', formatter: format_number, cellClasses :'default_reports_cell', width:'100px' },
		                {name: column_header.crystal, field: 'crystal', formatter: format_number, cellClasses :'default_reports_cell', width:'100px' },
		                {name: column_header.deuterium, field: 'deuterium', formatter: format_number, cellClasses :'default_reports_cell', width:'100px' },
		                {name: column_header.all_resources, field: 'all_resources', formatter: format_number, cellClasses :'default_reports_cell', width:'100px' },
		                {name: column_header.all_resis, field: 'all_resis', formatter: format_number, cellClasses :'default_reports_cell', width:'100px' },
		                {name: column_header.depth.header, field: 'depth', formatter: format_scandepth, cellClasses :'default_reports_cell', width:'100px' }
		                
		          ]];
	}

	searchgrid.set("structure",layout);
	searchgrid.set("autoHeight",galaxytool_autoheight);
	dijit.byId('ColumnDialog').hide();
	
	if (navigator.cookieEnabled == true) {
		// store selection at cookie
		var expiration = new Date();
		var expires = expiration.getTime() + (30 * 24 * 60 * 60 * 1000); // 30 days
		expiration.setTime(expires);
		document.cookie = "report_columns="+cookie_data+"; expires=" + expiration.toGMTString();
	}
}

function checkbox_selection(selection) {
	var item = null;
	var id = null;
	
	for (var i=0; i<searchgrid.get("rowCount"); i++) {
		item = searchgrid.getItem(i);
		if (item != null) {
			id = searchstore.getValues(item,"id");
			if (dijit.byId("deletebox"+id).get("value") == "true") {
				if (selection != true) {
					// remove selection
					dijit.byId("deletebox"+id).set("value", false);
				}
			} else {
				if (selection == true) {
					// add selection
					dijit.byId("deletebox"+id).set("value", true);
				}
			}
		}
	}
}

function column_selection(block_no, selection) {
	var from = 0;
	var to = 1;

	switch (block_no) {
		case 1: from = 0; to = 10; break; // general block
		case 2: from = 11; to = 14; break; // resources
		case 3: from = 15; to = 28; break; // fleet
		case 4: from = 29; to = 38; break; // defence
		case 5: from = 39; to = 56; break; // buildings
		case 6: from = 57; to = column_keys.length - 1; break; // tech
		default: return;
	}
	
	for (var i=from; i<=to; i++) {
		dijit.byId("column_"+column_keys[i]).set("value",selection);
	}
}

function delete_selected() {
	var item = null;
	var id = null;
	
	var id_collection = Array();
	var item_collection = Array();
	
	for (var i=0; i<searchgrid.get("rowCount"); i++) {
		item = searchgrid.getItem(i);
		if (item != null) {
			id = searchstore.getValues(item,"id");
			if (dijit.byId("deletebox"+id).get("value") == "true") {
				id_collection.push(parseInt(id));
				item_collection.push(item);
			}
		}
	}
	
	var xhrArgs = {
	        url: "ajax/ajax_report.php?type=delete",
	        content : {
	    		"id" : id_collection.join("|")
	    		},
	        handleAs: "json",
	        load: function(jsonData) {
	        	if (jsonData.messages != null) {
	        		showMessages(jsonData.messages);
	        	}
	        	
	        	dojo.forEach(item_collection, function(selectedItem){
	                if(selectedItem !== null){
	                    // Delete the item from the data store:
	                	searchstore.deleteItem(selectedItem);
	                }
	            });

	        },
	        error: function(error) {
				console.log("Error:");
				console.log(error);
	        }
	}	
	dojo.xhrPost(xhrArgs);
}

function galaxytool_load_cookie_data() {
	if (navigator.cookieEnabled == true) {
		// load last column selection from cookie
		if (document.cookie) {
			var cookie_data = document.cookie.split(";");
						
			for (var i=0; i< cookie_data.length; i++) {
				if (cookie_data[i].indexOf("report_columns=") > -1) {
					// uncheck all checked columns
					for (var j=0; j<column_keys.length; j++) {
						if (dijit.byId("column_"+column_keys[j]).get("value") == "true") {
							dijit.byId("column_"+column_keys[j]).set("value",false);
						}
					}
					
					var columns = cookie_data[i].split("|");
					columns[0] = columns[0].substring(0,columns[0].indexOf("report_columns="));
					for (var j=0; j< columns.length; j++) {
						if (columns[j] != "") {
							try {
								// check column
								dijit.byId("column_"+columns[j]).set("value",true);
							} catch(e) {
								console.log("Error at check column dijit");
								console.log(e);
							}
						}
					}
					break;
				}
			}
			
		}
	}
}

function showTooltip(e) {
	if (e.rowIndex < 0) { // header
        return;
    } else {
    	switch(e.cell.name) {
    		case column_header.metal:
    		case column_header.crystal:
    		case column_header.deuterium:
    		case column_header.depth.resources:
                var item = e.grid.getItem(e.rowIndex);
                // show ships needed to lift resources in tooltip
                
				// plunder algorithm
				// Let M, C and D be the amount of Metal, Crystal and Deuterium on the
				// planet. Let P be the cargo capacity of the ships of a particular kind.
				// Then the formula to compute the minimum number (N) of ships of this
				// kind that are needed is:
				//
				// N = 1 + Int ((Max (M + C + D, Min (0.75 * (M * 2 + C + D), M * 2 + D))) / (P * 2));
				//
				// where Int (X) returns the integer part of the number X, Max (X, Y)
				// returns the larger of the two numbers X and Y, and Min (X, Y) returns
				// the smaller of the two numbers X and Y.
                
                var metal     = parseInt(e.grid.store.getValue(item,"metal"));
                var crystal   = parseInt(e.grid.store.getValue(item,"crystal"));
                var deuterium = parseInt(e.grid.store.getValue(item,"deuterium"));
				var number_of_kt = Math.ceil ((Math.max(metal + crystal + deuterium, Math.min(0.75 * (metal * 2 + crystal + deuterium), metal * 2 + deuterium))) / (5000 * 2));
				var number_of_gt = Math.ceil ((Math.max(metal + crystal + deuterium, Math.min(0.75 * (metal * 2 + crystal + deuterium), metal * 2 + deuterium))) / (25000 * 2));
				var number_of_ss = Math.ceil ((Math.max(metal + crystal + deuterium, Math.min(0.75 * (metal * 2 + crystal + deuterium), metal * 2 + deuterium))) / (1500 * 2));
				var content = galaxytool_reports_for_all_res_text+":<br />";
				content += column_header.kt+": "+NumberFormat(number_of_kt)+"<br />";
				content += column_header.gt+": "+NumberFormat(number_of_gt)+"<br />";
				content += column_header.ss+": "+NumberFormat(number_of_ss)+"<br />";
                
                dijit.showTooltip(content, e.cellNode);
    		break;
    		
    		case column_header.fleet_resis:
    		case column_header.defence_resis:
    			var item = e.grid.getItem(e.rowIndex);
    			var amount = parseInt(e.grid.store.getValue(item, e.cell.field)) * 1000;
    			var number_of_rec = Math.ceil( (amount * (galaxytool_debris_rate/100)) / 20000);
    			
    			var content = galaxytool_reports_for_tf_text+":<br />";
    			content += galaxytool_reports_rec_text+": "+NumberFormat(number_of_rec)+"<br />";
    			dijit.showTooltip(content, e.cellNode);
    			
    		break;
    		
    	}
    };
}
function hideTooltip(e) {
    dijit.hideTooltip(e.cellNode);
};

function galaxytool_reports_init() {
	galaxytool_load_cookie_data();
	setTimeout("change_layout()",0);
	dojo.connect(searchgrid, "onCellMouseOver", showTooltip);
    dojo.connect(searchgrid, "onCellMouseOut", hideTooltip);
	
}

dojo.ready(galaxytool_reports_init);